local name, DB = ...

local frame = CreateFrame"Frame"

local party_units = {}
local raid_units = {}
local pet_of_unit = {}
local owner_of_unit = {}

do
	-- populate unit tables
	local function register_unit(tbl, unit, pet)
		table.insert(tbl, unit)
		pet_of_unit[unit] = pet
		owner_of_unit[pet] = unit
	end

	register_unit(party_units, "player", "pet")

	for i = 1, MAX_PARTY_MEMBERS do
		register_unit(party_units, ("party%d"):format(i),
					  ("partypet%d"):format(i))
	end

	for i = 1, MAX_RAID_MEMBERS do
		register_unit(raid_units, ("raid%d"):format(i),
					  ("raidpet%d"):format(i))
	end
end


frame.units = {}

frame:RegisterEvent"UNIT_PET"
frame:RegisterEvent"PARTY_MEMBERS_CHANGED"
frame:RegisterEvent"RAID_ROSTER_UPDATE"

function frame:Update()
	local units = (GetNumRaidMembers() == 0) and party_units or raid_units

	for _, unit in next, units do
		if UnitExists(unit) then
			self.units[UnitGUID(unit)] = UnitName(unit)
			local unitpet = pet_of_unit[unit]
			if unitpet and UnitExists(unitpet) then
				self.units[UnitGUID(unitpet)] = UnitName(unitpet) .. " (" .. UnitName(unit) .. ")"
			end
		end
	end
end

frame:SetScript("OnEvent", frame.Update)

function frame:GetNameByGuid(guid)
	return self.units[guid]
end

function frame:Save(db)
	local roster = db.Roster
	if not roster then
		roster = {}
		db.Roster = roster
	end
	for guid, name in next, self.units do
		roster[guid] = name
	end
end

function frame:Load(db)
	local roster = db.Roster
	if not roster then return end
	for guid, name in next, roster do
		self.units[guid] = name
	end
end

DB.roster = frame
